package com.hk.crm.web.filter;

import com.hk.crm.settings.domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入到验证有没有登录过的过滤器");
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
//        得到传过来的前端资源路径
        String path=request.getServletPath();
        if ("/login.jsp".equals(path)||"/settings/user/login.do".equals(path)){
//            如果是登录相关的资源 就放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
//        如果不为空 说明已经登录过 直接放行交还给服务器
            if (user!=null){
                filterChain.doFilter(servletRequest, servletResponse);

            }else {
//            没有登录过的话 重定向给登录页面
                response.sendRedirect(request.getContextPath()+"/login.jsp");
                System.out.println(request.getContextPath());
            }
        }
    }



    @Override
    public void destroy() {

    }
}
